package com.kaihong.template.utils;

import ohos.rpc.IRemoteObject;
import ohos.rpc.MessageOption;
import ohos.rpc.MessageParcel;
import ohos.rpc.RemoteException;
import ohos.utils.zson.ZSONObject;

import java.util.Map;

/**
 * 简化Js端回调
 */
public class JsObject {

    /**
     * 同步回调Js
     *
     * @param caller 用于回传给Js端的数据的本地对象 {@link MessageParcel}
     * @param data 回调给Js端的数据，k-v结构，建议添加一个code字段作为回调码，Js端根据回调码进行对应动作
     */
    public static void syncReply(MessageParcel caller, Map<String, Object> data) {
        caller.writeString(ZSONObject.toZSONString(data));
    }

    /**
     * 异步回调Js
     *
     * @param caller Js端的远程调用对象 {@link IRemoteObject}
     * @param code 回调码，Js端根据回调码进行对应动作
     * @param data 回调给Js端的数据，k-v结构
     * @param option 回调方式配置，设置同步异步回调方式以及超时{@link MessageOption}
     */
    public static void asyncReply(IRemoteObject caller, int code, Map<String, Object> data, MessageOption option) {
        MessageParcel responseData = MessageParcel.obtain();
        responseData.writeString(ZSONObject.toZSONString(data));
        // 传递个默认的对象给Js端
        MessageParcel reply = MessageParcel.obtain();
        try {
            caller.sendRequest(code, responseData, reply, option);
        } catch (RemoteException exception) {
            exception.printStackTrace();
        } finally {
            responseData.reclaim();
            reply.reclaim();
        }
    }
}
